package cn.ciis.basic.directive;

import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

import java.io.IOException;

/**
 * 自动补齐0个数   12--》》path(x.aa,5)===>00012
 */
public class PatchDriective extends Directive {

    private Expr parmValueExpr;
    private Expr parmNumExpr;
    private int paraNum;

    public PatchDriective(){}

    @Override
    public void setExprList(ExprList exprList){
        paraNum=exprList.length();
        if (paraNum>2){
            throw  new ParseException("Wrong number parameter of #patch directive, two parameters allowed at most", location);
        }else{
            if (paraNum == 2) {
                parmValueExpr = exprList.getExpr(0);
                parmNumExpr = exprList.getExpr(1);
            }
        }
    }

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        if (paraNum == 2) {
            outputPlacesNum(env, scope, writer);
        } else {
            stat.exec(env, scope, writer);
        }
    }

    private void outputPlacesNum(Env env, Scope scope, Writer writer){
        Object value =parmValueExpr.eval(scope);
        Object num = parmNumExpr.eval(scope);
        String s =String.format("%0"+num+"d",Integer.parseInt(value.toString()));
        try {
            writer.write(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
